package cn.gzsf;

import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 使用单元测试JDBC
 *
 */
public class TestJDBC {

    @Test//在普通方法上添加@Test，称为单元测试方法，该方法可以单独执行
    //单元测试方法方法要满足以下条件：
    //1，无返回值，用void修饰
    //2，方法无参数
    //3,普通方法，不要用static修饰
    public void testAdd(){
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
             conn = JDBCUtil.getConn();
             stat = conn.createStatement();
             String sql = "insert into account values (null,'zhangsan',3000.0)";
             int rows = stat.executeUpdate(sql);
             System.out.println(rows==1?"成功":"失败");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,stat,rs);
        }
    }

    @Test
    public void testUpdate(){
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn  = JDBCUtil.getConn();
            stat = conn.createStatement();
            String sql = "update account set name='lisi',money=5000 where id=8";
            int rows = stat.executeUpdate(sql);
            System.out.println(rows==1?"成功":"失败");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,stat,rs);
        }
    }

    @Test
    public void testDelete(){
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConn();
            stat = conn.createStatement();
            String sql = "delete from account where id=8";
            int rows = stat.executeUpdate(sql);
            System.out.println(rows==1?"成功":"失败");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,stat,rs);
        }
    }
    //查询id为1的账户信息
    @Test
    public void testSelect(){
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            //conn = JDBCUtil.getConn();
            conn = JDBCUtil2.getConn();
            stat = conn.createStatement();
            String sql = "select * from account where id=1";
            //增删改用executeUpdate，查询用executeQuery
            rs = stat.executeQuery(sql);
            if(rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString(2);
                double money = rs.getDouble(3);
                System.out.println(id+":"+name+":"+money);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,stat,rs);
        }
    }

}
